package com.powerunion.extjs.data;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.powerunion.datacollection.persistence.db.jdbc.operator.QueryOperator;
import com.powerunion.extjs.BasePara;
import com.powerunion.extjs.ListRange;
import com.powerunion.extjs.TreeNode;
import com.powerunion.extjs.XmlParser;

public class TreeDataLoader extends DbDataLoader {
	private TreeNode pNode=null;
	private String depth="";
	public TreeDataLoader(TreeNode treenode,BasePara paravo){
		super(paravo);
		this.pNode = treenode;
	}
	
	public void wrapSql() throws Exception{
		XmlParser parser = new XmlParser();
		this.paravo.setXmlFileName("tree_sql_config.xml");
		parser.loadSql(this.paravo); 
		
		depth = this.paravo.getTreeCfg().get("depth")+"";//深度
		if(!depth.equals("1")){ //不是一级树就把node的id当作参数加入进去
			ArrayList vl = this.paravo.getBaseValue();
			if(null==vl){
				vl = new ArrayList();
			}
			vl.add(this.pNode.getId());
			this.paravo.setBaseValue(vl);
		}
		
		this.paravo.addWhereSql();
		this.paravo.addOrderSql();
	}
	
	public void collectToMap() {
		ArrayList al = null;
		HashMap map = null;
		String[] colNameArray = convert.contvertColumnName( this.paravo.getSql());
//		colNameArray[0]="text";
//		colNameArray[1]="id";		
		al = new ArrayList();
		if (!rs.isEmpty()) {
			String iconCls = pNode.getCiconCls();
			boolean isLeaf = !"".equals(depth) && pNode.getClevel().equals(depth);
		
			for (Iterator it = rs.iterator(); it.hasNext();) {
				Map obj = (Map)it.next();
				map = new HashMap();
				for (int i = 0; i < colNameArray.length; i++) {
					String tag = colNameArray[i].toUpperCase();
					Object value = obj.get(tag);
//					if(tag.indexOf("childNum")>-1){
//						continue;
//					}
					if(i==0){
						map.put("text", value);
					}else if(i == 1){
						map.put("id", value);
					}else{
						map.put(tag, value);
					}
					
				}
				if(isLeaf) map.put("leaf", "true");
				if(null!=iconCls && ""!=iconCls) {
					map.put("iconCls", iconCls);
				}else{
					map.put("iconCls", isLeaf?"icon-base":"icon-pkg");
				}
				al.add(map);
			}
		}
		range = new ListRange();
		range.setData(al);
		//range.setTotalSize(this.totalCount);
		//this.setMetaData(colNameArray);
	}
	
	public Collection getRecords(String sql, Object params,String type) throws Exception {
		Collection col = null;
		try {
			QueryOperator query = new QueryOperator();
			query = convert.getParams(query,  params);
			query.setSql(sql);
			query.access();
			if (query.resultSetAvailable()) {// 检查结果集是否可用
				// 获取并处理记录集
				col = query.getSqlResultSet();
			}
			
		} catch (Exception e) {
			System.out.println("error_sql:"+sql);
			throw new Exception("get all record error-->"+e.getMessage(),e.getCause());
		}
		return col;
	}
}
